"""
微信小程序服务
"""
import httpx
from typing import Optional, Dict
from app.core.config import settings
from app.core.logger import logger


class WeChatService:
    """微信小程序服务"""
    
    def __init__(self):
        self.appid = settings.WECHAT_APPID
        self.secret = settings.WECHAT_SECRET
        self.use_mock = settings.WECHAT_USE_MOCK
        self.code2session_url = "https://api.weixin.qq.com/sns/jscode2session"
        logger.info(f"🔧 微信服务初始化: appid={self.appid}, secret={'***' + self.secret[-4:] if self.secret else 'None'}, use_mock={self.use_mock}")
    
    async def code_to_session(self, code: str) -> Optional[Dict]:
        """
        通过 code 换取 openid 和 session_key
        
        Args:
            code: 微信登录凭证 code
            
        Returns:
            {
                "openid": "用户唯一标识",
                "session_key": "会话密钥",
                "unionid": "用户在开放平台的唯一标识"
            }
        """
        # 开发环境下使用 Mock 模式
        if self.use_mock:
            logger.warning(f"⚠️  开发模式：使用 Mock 微信登录（WECHAT_USE_MOCK=True）")
            logger.debug(f"   - code={code}")
            logger.debug(f"   - appid={self.appid}")
            return {
                "openid": f"mock_openid_{code[:8]}",
                "session_key": "mock_session_key",
                "unionid": None
            }
        
        params = {
            "appid": self.appid,
            "secret": self.secret,
            "js_code": code,
            "grant_type": "authorization_code"
        }
        
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(self.code2session_url, params=params)
                data = response.json()
                
                logger.info(f"📱 微信 API 响应: {data}")
                
                # 检查错误
                if "errcode" in data and data["errcode"] != 0:
                    logger.error(f"❌ 微信登录错误 [errcode={data.get('errcode')}]: {data.get('errmsg')}")
                    return None
                
                return {
                    "openid": data.get("openid"),
                    "session_key": data.get("session_key"),
                    "unionid": data.get("unionid")
                }
        except Exception as e:
            logger.exception(f"❌ 微信登录异常: {e}")
            return None
    
    async def get_phone_number(self, code: str, access_token: str) -> Optional[Dict]:
        """
        获取用户手机号
        
        Args:
            code: 手机号获取凭证
            access_token: 接口调用凭证
            
        Returns:
            {
                "phoneNumber": "用户手机号",
                "purePhoneNumber": "没有区号的手机号",
                "countryCode": "区号"
            }
        """
        url = f"https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={access_token}"
        
        try:
            async with httpx.AsyncClient() as client:
                response = await client.post(url, json={"code": code})
                data = response.json()
                
                if data.get("errcode") != 0:
                    print(f"获取手机号错误: {data.get('errmsg')}")
                    return None
                
                phone_info = data.get("phone_info", {})
                return {
                    "phoneNumber": phone_info.get("phoneNumber"),
                    "purePhoneNumber": phone_info.get("purePhoneNumber"),
                    "countryCode": phone_info.get("countryCode")
                }
        except Exception as e:
            print(f"获取手机号异常: {e}")
            return None
    
    async def get_access_token(self) -> Optional[str]:
        """
        获取小程序全局唯一后台接口调用凭据
        
        Returns:
            access_token 字符串
        """
        url = "https://api.weixin.qq.com/cgi-bin/token"
        params = {
            "grant_type": "client_credential",
            "appid": self.appid,
            "secret": self.secret
        }
        
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(url, params=params)
                data = response.json()
                
                if "access_token" in data:
                    return data["access_token"]
                else:
                    print(f"获取 access_token 失败: {data}")
                    return None
        except Exception as e:
            print(f"获取 access_token 异常: {e}")
            return None


# 创建全局实例
wechat_service = WeChatService()

